package android.twitter.clientroid;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LoginActivity extends Activity
{
	private Twitter twitter;
	private CommonsHttpOAuthProvider provider;
	private CommonsHttpOAuthConsumer consumer;

	private String CONSUMER_KEY = Constants.CONSUMER_KEY;
	private String CONSUMER_SECRET = Constants.CONSUMER_SECRET;
	private String CALLBACK_URL = Constants.callback_scheme + "://" + Constants.callback_url;

	private Button buttonLogin;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginpage);
		
		//SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
		
		//Toast.makeText(AuthActivity.this, "Please login", Toast.LENGTH_LONG).show();
		System.out.println("onCreate' teyim");
		System.setProperty("http.keepAlive", "false");
		
		//check for saved log in details..
		checkForSavedLogin();

		//set consumer and provider on the Application service
		getConsumerProvider();
		
		//Define login button and listener
		buttonLogin = (Button)findViewById(R.id.ButtonLogin);
		buttonLogin.setOnClickListener(new OnClickListener() {  
			public void onClick(View v) {
				askOAuth();
			}
		});

	}

	private void checkForSavedLogin()
	{
		System.out.println("checked for saved login");
		// Get Access Token and persist it
		AccessToken a = getAccessToken();
		if (a==null) return;	//if there are no credentials stored then return to usual activity

		// initialize Twitter4J
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		twitter.setOAuthAccessToken(a);
		((TwitterApplication)getApplication()).setTwitter(twitter);
		startFirstActivity();
		finish();
	}

	private void startFirstActivity()
	{
		System.out.println("STARTING FIRST ACTIVITY!");
		Intent i = new Intent(this, TimeLineActivity.class);
		startActivityForResult(i, Constants.ACTIVITY_LATEST_TWEETS);
	}

	private AccessToken getAccessToken()
	{
		SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
		String token = settings.getString("accessTokenToken", "");
		String tokenSecret = settings.getString("accessTokenSecret", "");
		if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
			return new AccessToken(token, tokenSecret);
		}
		return null;
	}

	private void askOAuth()
	{
		Log.v("state", "askOAuth' dayim");
		try {
			// fetching the request token
			consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
			provider = new CommonsHttpOAuthProvider(
					"http://twitter.com/oauth/request_token", 
					"http://twitter.com/oauth/access_token", 
					"http://twitter.com/oauth/authorize"
					);
			System.out.println("authUrl' yi olusturmak uzereyim");
			System.out.println("isOAuth10a: " + provider.isOAuth10a());
			String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
			System.out.println("authUrl: " + authUrl);
			Toast.makeText(this, "Please authorize this app", Toast.LENGTH_LONG).show();
			setConsumerProvider();
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
		} catch (Exception e) {
			//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			System.out.println(e.getMessage());
		}
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		System.out.println("RESUMING!!");
		if (this.getIntent()!=null && this.getIntent().getData()!=null){
			Uri uri = this.getIntent().getData();
			if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
				String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
				try {
					// this will populate token and token_secret in consumer
					provider.retrieveAccessToken(consumer, verifier);

					// Get Access Token and persist it
					AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
					storeAccessToken(a);

					// initialize Twitter4J
					twitter = new TwitterFactory().getInstance();
					twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
					twitter.setOAuthAccessToken(a);
					((TwitterApplication)getApplication()).setTwitter(twitter);
					//Log.e("Login", "Twitter Initialized");
					
					startFirstActivity();

				} catch (Exception e) {
					//Log.e(APP, e.getMessage());
					e.printStackTrace();
					Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	private void storeAccessToken(AccessToken a)
	{
		System.out.println("storeAccessToken' dayim");
		SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("accessTokenToken", a.getToken());
		editor.putString("accessTokenSecret", a.getTokenSecret());
		editor.commit();
	}

	private void getConsumerProvider()
	{
		System.out.println("getConsumerProvider' dayim");
		CommonsHttpOAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
		if (p!=null)
		{
			provider = p;
		}
		CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
		if (c!=null)
		{
			consumer = c;
		}
	}

	private void setConsumerProvider()
	{
		System.out.println("setConsumerProvider' dayim");
		if (provider!=null)
		{
			((TwitterApplication)getApplication()).setProvider(provider);
		}
		if (consumer!=null){
			((TwitterApplication)getApplication()).setConsumer(consumer);
		}
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
        	int pid = android.os.Process.myPid(); 
        	android.os.Process.killProcess(pid);
        }
        return super.onKeyDown(keyCode, event);
    }

}

